package com.lanou3g.bbs.dao;

import com.lanou3g.bbs.entity.User;
import com.lanou3g.bbs.util.CloseAll;
import com.lanou3g.bbs.util.JDBCUtil;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class Dao {
    public boolean loginDao(User user) {
        try {
            Connection conn = JDBCUtil.getConn();
            String sql = "SELECT COUNT( * ) FROM user WHERE user_name = ? AND user_password= ? ";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, user.getName());
            statement.setString(2, user.getPwd());
            ResultSet rs = statement.executeQuery();
            boolean canlogin = false;
            if (rs.next()) {
                int count = rs.getInt(1);
                canlogin = count > 0;
            }
            CloseAll.CloseA(statement, rs);
            return canlogin;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean hasThisName(User user) {
        String sql = "SELECT COUNT( * ) FROM user WHERE user_name = ?";
        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, user.getName());
            ResultSet resultSet = statement.executeQuery();
            resultSet.next();
            int count = resultSet.getInt(1);
            CloseAll.CloseA(resultSet, resultSet);
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean register(User user) {
        Connection conn = JDBCUtil.getConn();
        try {
            String sql = "INSERT INTO user(user_name,user_password,user_gender,role_id)VAlUES( ?, ?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, user.getName());
            statement.setString(2, user.getPwd());
            statement.setString(3, user.getGender());
            statement.setString(4, "2");
            statement.executeUpdate();
            CloseAll.CloseA(statement, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }
}
